package com.yisin.ssh2;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class EventCenter {

	private static Map<EventName, List<EventHandler>> EVENTS = new HashMap<EventName, List<EventHandler>>();

	/**
	 * 向事件中心广播一个时间，驱使事件中心执行该事件的处理器
	 * 
	 * @param eventName
	 * @param param
	 */
	public static void fire(EventName eventName, Object... param) {
		List<EventHandler> handlerList = EVENTS.get(eventName);
		if (null == handlerList || handlerList.isEmpty()) {
			return;
		}
		for (EventHandler handler : handlerList) {
			try {
				handler.handle(param);
			} catch (Exception e) {
				fire(EventName.exception_occured, e);
			}
		}
	}

	/**
	 * 将自己注册为事件中心的某个事件的处理器
	 * 
	 * @param eventName
	 * @param handler
	 */
	public static void register(EventName eventName, EventHandler handler) {
		List<EventHandler> handlerList = EVENTS.get(eventName);
		if (null == handlerList) {
			handlerList = new LinkedList<EventHandler>();
		}

		handlerList.add(handler);
		EVENTS.put(eventName, handlerList);
	}

}
